﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyAdmin_HoaDon_AM : System.Web.UI.Page
{
    string tkTenDN = null;
    string tkDiaChi = null;
    DateTime? tkTuNgay = null;
    DateTime? tkDenNgay = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        {
            // xử lý quyền xem
            ((CommandField)gvDSNCC_GiangHang.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtChiTietGiangHang.Fields[dtChiTietGiangHang.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        //Tim kiem theo parameter truyen vao theo cu phap: [TenDN=...] [TenSP=...][&GiaTu=...][&GiaDen=...]
        tkTenDN = Request.Params["TenDN"];
        tkDiaChi = Request.Params["DiaChi"];
        if (Request.Params["TuNgay"] != null) tkTuNgay = DateTime.Parse(Request.Params["TuNgay"]);
        if (Request.Params["DenNgay"] != null) tkDenNgay = DateTime.Parse(Request.Params["DenNgay"]);

        if (!IsPostBack)
        {
            initTextBox();
        }
        
        List<int> checkedCheckBoxRowIndex = getCheckedCheckBoxRowIndexes(gvDSNCC_GiangHang);
        initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxRowIndex);

        if ((tkTenDN != null || tkDiaChi != null || tkTuNgay != null || tkDenNgay != null) && gvDSNCC_GiangHang.Rows.Count == 0)
        {
            lblTBKhongTimThay.Visible = true;
            dtChiTietGiangHang.Visible = false;
        }

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }

    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSNCC_GiangHang.Rows[rowIndex].Cells[lastCellIndex].FindControl("checkXoa")).Checked = true;
        }
    }
    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSNCC_GiangHang)
    {
        if (gvDSNCC_GiangHang.Rows.Count == 0)
        {
            return null;
        }

        List<int> rowIndexes = new List<int>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }
    private void initDataSource()
    {
        refreshGV();
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.SelectedIndex == -1 ? 0 : gvDSNCC_GiangHang.SelectedIndex;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    private void refreshGV()
    {
        gvDSNCC_GiangHang.DataSource = DataAccess_Layer.Order_DAC.tim(tkTenDN, tkDiaChi, tkTuNgay, tkDenNgay);
        gvDSNCC_GiangHang.DataBind();
    }
    private void initTextBox()
    {
        txtTenDNKH_TK.Text = (tkTenDN == null) ? txtTenDNKH_TK.Text : tkTenDN;
        txt_DiaChiGH.Text = (tkDiaChi == null) ? txt_DiaChiGH.Text : tkDiaChi;
        calTuNgayDH_TK.SelectedDate = (tkTuNgay == null) ? DateTime.Now.Date : tkTuNgay.Value;
        calDenNgayDH_TK.SelectedDate = (tkDenNgay == null) ? DateTime.Now.Date : tkDenNgay.Value;
    }

    protected void gvDSNCC_GiangHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, gvDSNCC_GiangHang.PageCount - 1);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count - 1;

        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }
    private void refreshDetailViewPageIndex()
    {
        dtChiTietGiangHang.DataBind();
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void btnTimKiem_NCCGH_Click(object sender, EventArgs e)
    {
        string tenDN = txtTenDNKH_TK.Text.Length == 0 ? null : txtTenDNKH_TK.Text;
        string tenNCC = txt_DiaChiGH.Text.Length == 0 ? null : txt_DiaChiGH.Text;
        DateTime? tuNgay = calTuNgayDH_TK.SelectedDate;
        DateTime? denNgay = calDenNgayDH_TK.SelectedDate;

        string url = "HoaDon_AM.aspx?TuNgay=" + tuNgay.Value.ToShortDateString() + "&DenNgay=" + denNgay.Value.ToShortDateString();

        if (tenDN != null) url += "&TenDN=" + tenDN;
        if (tenNCC != null) url += "&DiaChi=" + tenNCC;

        Response.Redirect(url);
    }

    protected void LQDSNCC_GiangHang_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSNCC_GiangHang.DataSource;
    }

    protected void gvDSNCC_GiangHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, e.NewPageIndex);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count > 0 ? 0 : -1;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[1].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));

        try
        {
            DataAccess_Layer.Order_DAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";            
        }

        initDataSource();
        refreshDetailViewPageIndex();
    }
    protected void LQDSNCC_GiangHang_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {
        DataAccess_Layer.Order newOrder = (DataAccess_Layer.Order)e.NewObject;
        lblThongBaoDTView.Visible = true;
        try
        {
            DataAccess_Layer.Order_DAC.update(newOrder);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newOrder.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newOrder.ID;
        }
        
        e.Cancel = true;
    }

    protected void cbbLSP_DataBound(object sender, EventArgs e)
    {
        handleCBXDataBound("cbxCustomer", "lblCustomerID_ForEdit");
    }
    private void handleCBXDataBound(string cbxID, string lblID)
    {
        DropDownList cbbLSP = (DropDownList)dtChiTietGiangHang.FindControl(cbxID);
        Label txtMaCLSP = (Label)dtChiTietGiangHang.FindControl(lblID);

        if (dtChiTietGiangHang.CurrentMode == DetailsViewMode.Edit)
        {
            cbbLSP.SelectedValue = txtMaCLSP.Text;
        }
        else if (dtChiTietGiangHang.CurrentMode == DetailsViewMode.Insert)
        {
            txtMaCLSP.Text = cbbLSP.SelectedValue;
        }
    }

    protected void cbbLSP_SelectedIndexChanged(object sender, EventArgs e)
    {
        handleCBXSelectedIndexChanged("cbxCustomer", "lblCustomerID_ForEdit");
    }
    private void handleCBXSelectedIndexChanged(string cbxID, string lblID)
    {
        DropDownList cbbLSP = (DropDownList)dtChiTietGiangHang.FindControl(cbxID);
        Label txtMaCLSP = (Label)dtChiTietGiangHang.FindControl(lblID);
        txtMaCLSP.Text = cbbLSP.SelectedValue;
    }

    protected void cbbTT_DataBound(object sender, EventArgs e)
    {
        handleCBXDataBound("cbxTrangThai", "lblOrderState_ForEdit");
    }
    protected void cbbTT_SelectedIndexChanged(object sender, EventArgs e)
    {
        handleCBXSelectedIndexChanged("cbxTrangThai", "lblOrderState_ForEdit");
    }

    protected void cbbNVC_DataBound(object sender, EventArgs e)
    {
        handleCBXDataBound("cbxNVC", "lblNhaVC");
    }
    protected void cbbNVC_SelectedIndexChanged(object sender, EventArgs e)
    {
        handleCBXSelectedIndexChanged("cbxNVC", "lblNhaVC");
    }
    protected void LQDSHoaDon_AM_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.Order newOrder = (DataAccess_Layer.Order)e.Result;
        
        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;       
    }
    protected void dtChiTietGiangHang_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        Calendar cal = (Calendar)dtChiTietGiangHang.FindControl("CreatedDateInsertCALENDAR");
        cal.SelectedDate = DateTime.Now;
    }
}